package servlet;

import com.alibaba.fastjson.JSON;
import entity.Approach;
import service.ApproachService;
import service.impl.ApproachServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ApproachServlet")
public class ApproachServlet extends HttpServlet {
    ApproachService approachService = new ApproachServiceImpl();
    ResultSet rs;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String opr = req.getParameter("opr");
        if (opr.equals("approaches")){
            List payList = new ArrayList();
            Approach pay = new Approach();
            List incomeList = new ArrayList();
            Approach income = new Approach();
            rs = approachService.selectApproaches();
            try{
                while (rs.next()){
                    int aid =  rs.getInt("aid");
                    String approach = rs.getString("approach");
                    int sid = rs.getInt("sid");
                    String url = rs.getString("url");
                    String urlselected = rs.getString("urlselected");

                    if (sid == 1){
                        pay = new Approach(aid,approach,sid,url,urlselected);
                        payList.add(pay);
                    }else if (sid == 2){
                        income = new Approach(aid,approach,sid,url,urlselected);
                        incomeList.add(income);
                    }

                }
            }catch (Exception e){
                e.printStackTrace();
            }


            Map approach = new HashMap();
            approach.put("payList",payList);
            approach.put("incomeList",incomeList);
            String approachJson = JSON.toJSONString(approach);
            out.print(approachJson);

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
